package com.jeehentor.generate.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeehentor.common.exception.HentorException;
import com.jeehentor.generate.dto.GenFormSaveDTO;
import com.jeehentor.generate.dto.SysGenFormDTO;
import com.jeehentor.generate.dto.SysGenFormWidgetDTO;
import com.jeehentor.generate.entity.SysGenForm;
import com.jeehentor.generate.entity.SysGenFormWidget;
import com.jeehentor.generate.entity.SysGenModel;
import com.jeehentor.generate.mapper.SysGenFormMapper;
import com.jeehentor.generate.mapper.SysGenModelMapper;
import com.jeehentor.generate.service.ISysGenFormService;
import com.jeehentor.generate.service.ISysGenFormWidgetService;
import com.jeehentor.utils.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 表单配置主表 服务实现类
 * </p>
 *
 * @author wzd
 * @since 2024-05-17
 */
@Service
@RequiredArgsConstructor
public class SysGenFormServiceImpl extends ServiceImpl<SysGenFormMapper, SysGenForm> implements ISysGenFormService {

    private final ISysGenFormWidgetService sysGenFormWidgetService;

    private final SysGenModelMapper sysGenModelMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateForm(GenFormSaveDTO dto) {
        if(StringUtils.isBlank(dto.getFormConfig().getModelName())){
            throw new HentorException("数据对象名称不能为空!");
        }
        LambdaQueryWrapper<SysGenModel> sysGenModelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysGenModelLambdaQueryWrapper.eq(SysGenModel::getTableName, dto.getFormConfig().getModelName());
        SysGenModel sysGenModel = sysGenModelMapper.selectOne(sysGenModelLambdaQueryWrapper);
        SysGenForm sysGenForm1 = new SysGenForm();
        BeanUtils.copyProperties(dto.getFormConfig(), sysGenForm1);
        if(StringUtils.isNotBlank(dto.getFormConfig().getId())){
            //更新
            SysGenForm sysGenForm = this.getById(dto.getFormConfig().getId());
            dto.getFormConfig().setId(sysGenForm.getId());
            if(CollectionUtils.isNotEmpty(dto.getFormConfig().getCustomClass())){
                sysGenForm1.setCustomClass(String.join(",", dto.getFormConfig().getCustomClass()));
            }
            if(CollectionUtils.isNotEmpty(dto.getFormConfig().getDataSources())){
                sysGenForm1.setDataSources(JSONObject.toJSONString(dto.getFormConfig().getDataSources()));
            }
            sysGenForm1.setUpdateBy(SecurityUtil.getCurrentUser().getId());
            updateById(sysGenForm1);
            LambdaQueryWrapper<SysGenFormWidget> sysGenFormWidgetLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysGenFormWidgetLambdaQueryWrapper.eq(SysGenFormWidget::getFormId, sysGenForm.getId());
            sysGenFormWidgetService.remove(sysGenFormWidgetLambdaQueryWrapper);
            saveBatchWidget(dto, sysGenForm1.getId());
        }else {
            //新增
            dto.getFormConfig().setModelId(sysGenModel!= null?sysGenModel.getId() : null);
            if(CollectionUtils.isNotEmpty(dto.getFormConfig().getCustomClass())){
                sysGenForm1.setCustomClass(String.join(",", dto.getFormConfig().getCustomClass()));
            }
            if(CollectionUtils.isNotEmpty(dto.getFormConfig().getDataSources())){
                sysGenForm1.setDataSources(JSONObject.toJSONString(dto.getFormConfig().getDataSources()));
            }
            sysGenForm1.setCreateBy(SecurityUtil.getCurrentUser().getId());
            save(sysGenForm1);
            saveBatchWidget(dto, sysGenForm1.getId());
        }
    }
    private void saveBatchWidget(GenFormSaveDTO dto, String formId){
        ArrayList<SysGenFormWidget> sysGenFormWidgets = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(dto.getWidgetList())){
            dto.getWidgetList().forEach(x->{
                SysGenFormWidget sysGenFormWidget = new SysGenFormWidget();
                BeanUtils.copyProperties(x, sysGenFormWidget);
                sysGenFormWidget.setWidgetId(x.getId());
                sysGenFormWidget.setId(null);
                sysGenFormWidget.setFormId(formId);
                sysGenFormWidget.setCols(JSONObject.toJSONString(x.getCols()));
                sysGenFormWidget.setOptions(JSONObject.toJSONString(x.getOptions()));
                sysGenFormWidget.setCreateBy(SecurityUtil.getCurrentUser().getId());
                sysGenFormWidgets.add(sysGenFormWidget);
            });
            sysGenFormWidgetService.saveBatch(sysGenFormWidgets);
        }
    }

    @Override
    public GenFormSaveDTO selectFormDetail(GenFormSaveDTO dto) {
        GenFormSaveDTO genFormSaveDTO = new GenFormSaveDTO();
        if(StringUtils.isBlank(dto.getFormConfig().getId())){
            throw new HentorException("表单id不能为空!");
        }
        SysGenForm sysGenForm = this.getById(dto.getFormConfig());
        if(sysGenForm != null){
            SysGenFormDTO sysGenFormDTO = new SysGenFormDTO();
            BeanUtils.copyProperties(sysGenForm, sysGenFormDTO);
            if(StringUtils.isNotBlank(sysGenForm.getCustomClass())){
                sysGenFormDTO.setCustomClass(Arrays.stream(sysGenForm.getCustomClass().split(",")).toList());
            }else {
                sysGenFormDTO.setCustomClass(new ArrayList<>());
            }
            if(StringUtils.isNotBlank(sysGenForm.getDataSources())){
                ArrayList<Map<String, Object>> maps = new ArrayList<>();
                JSONArray listObjectThir = JSONArray.parseArray(sysGenForm.getDataSources());
                for(Object mapList : listObjectThir){
                    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                    for (Object entry : ((Map)mapList).entrySet()){
                        stringObjectHashMap.put(entry.toString(), ((Map)mapList).get(entry));
                    }
                    maps.add(stringObjectHashMap);
                }
                sysGenFormDTO.setDataSources(maps);
            }else {
                sysGenFormDTO.setDataSources(new ArrayList<>());
            }
            genFormSaveDTO.setFormConfig(sysGenFormDTO);
            LambdaQueryWrapper<SysGenFormWidget> sysGenFormWidgetLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysGenFormWidgetLambdaQueryWrapper.eq(SysGenFormWidget::getFormId, sysGenForm.getId());
            List<SysGenFormWidget> sysGenFormWidgets = sysGenFormWidgetService.list(sysGenFormWidgetLambdaQueryWrapper);
            ArrayList<SysGenFormWidgetDTO> sysGenFormWidgetList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(sysGenFormWidgets)){
                sysGenFormWidgets.forEach(x->{
                    SysGenFormWidgetDTO sysGenFormWidgetDTO = new SysGenFormWidgetDTO();
                    BeanUtils.copyProperties(x, sysGenFormWidgetDTO);
                    if(StringUtils.isNotBlank(x.getOptions())){
                        sysGenFormWidgetDTO.setOptions(JSONObject.parseObject(x.getOptions(), Map.class));
                        JSONArray jsonArray = JSONArray.parseArray(x.getCols());
                        List<Map<String, Object>> listMap = new ArrayList<>();
                        // 遍历JSONArray，将每个JSONObject转换为Map并添加到listMap中
                        if(jsonArray != null){
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                Map<String, Object> map = jsonObject.to(Map.class);
                                listMap.add(map);
                            }
                            sysGenFormWidgetDTO.setCols(listMap);
                        }
                    }
                    sysGenFormWidgetList.add(sysGenFormWidgetDTO);
                });
            }
            genFormSaveDTO.setWidgetList(sysGenFormWidgetList);
        }
        return genFormSaveDTO;
    }
}
